<template>
  <div>
    <el-form ref="form" label-width="100px" :inline="false">
      <el-form-item label="sku名称">
        <el-input placeholder="SKU名称" v-model="skuParams.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input placeholder="价格(元)" v-model="skuParams.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(克)">
        <el-input placeholder="重量(克)" v-model="skuParams.weight"></el-input>
      </el-form-item>
      <el-form-item label="sku描述">
        <el-input
          placeholder="sku描述"
          type="textarea"
          v-model="skuParams.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true">
          <el-form-item
            v-for="(item) in attrArr"
            :key="item.id"
            :label="item.attrName"
          >
            <el-select placeholder="请选择" v-model="item.attrIdAndAttrValueId">
              <el-option
                v-for="(attrValue) in item.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${item.id}:${attrValue.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true">
          <el-form-item
            v-for="(item) in saleArr"
            :key="item.id"
            :label="item.saleAttrName"
          >
            <el-select placeholder="请选择" v-model="item.saleIdAndValueId">
              <el-option
                v-for="(saleValue) in item.spuSaleAttrValueList"
                :key="saleValue.id"
                :label="saleValue.saleAttrValueName"
                :value="`${item.id}:${saleValue.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border :data="imgArr" ref="imgTableInstance">
          <el-table-column
            type="selection"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column label="图片">
            <template #="{ row }">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.imgUrl"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #="{ row }">
              <el-button
                type="warning"
                size="small"
                @click="setDefaultImg(row)"
              >
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button size="default" @click="cancal">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reqAttrInfoList } from '@/api/product/attr'
import type { AttrResponseData } from '@/api/product/attr/type'
import { reqAddSku, reqImageList, reqSaleAttrList } from '@/api/product/spu'
import type {
  SaleAttrResponseData,
  SpuHasImg,
  SkuData,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus/lib/components/index.js'
import { ref, reactive } from 'vue'

//平台属性
let attrArr = ref<any>([])
//销售属性
let saleArr = ref<any>([])
//照片的数据
let imgArr = ref<any>([])
// 获取table组件实例
let imgTableInstance = ref<any>()

//收集SKU的参数
let skuParams = reactive<SkuData>({
  //父组件传递过来的数据
  category3Id: '', //三级分类的ID
  spuId: '', //已有的SPU的ID
  tmId: '', //SPU品牌的ID
  //v-model收集
  skuName: '', //sku名字
  price: '', //sku价格
  weight: '', //sku重量
  skuDesc: '', //sku的描述
  skuAttrValueList: [], // 平台属性的收集
  skuSaleAttrValueList: [], // 销售属性的收集
  skuDefaultImg: '', //sku图片地址
})

// 取消按钮的回调
const cancal = () => {
  $emit('changeScene', { scenes: 0, action: '' })
}

// 当前子组件的方法对外暴露
const initAddSku = async (c1Id: number | string, c2Id: number | string, spu: any,) => {
  console.log('initAddSku row->', spu);
  // 首先清空所有之前添加的数据
  skuParams.skuName = ''
  skuParams.price = ''
  skuParams.weight = ''
  skuParams.skuDesc = ''
  attrArr.value = []
  saleArr.value = []
  imgArr.value = []
  
  // 获取平台属性
  let result: AttrResponseData = await reqAttrInfoList(
    c1Id,
    c2Id,
    spu.category3Id,
  )
  // 获取对应的销售属性
  let result1: SaleAttrResponseData = await reqSaleAttrList(spu.id)
  // 获取照片墙的数据
  let result2: SpuHasImg = await reqImageList(spu.id)

  attrArr.value = result.data // 存储平台属性
  saleArr.value = result1.data // 存储对应SPU的销售属性
  imgArr.value = result2.data // 存储对应SPU的照片墙

  // 收集数据
  skuParams.category3Id = spu.category3Id
  skuParams.spuId = spu.id
  skuParams.tmId = spu.tmId
}

// 设置默认图片的回调函数
const setDefaultImg = (row: any) => {
  console.log('row->', row, imgTableInstance)
  // 由于我们要求当我们单击对应的行的“设置默认”按钮时，还需要默认勾选上该行前面的复选框的按钮，而且我们还要求只能勾选一个，代表一个sku只有选一张图片。
  // 这里我们首先在勾选前，设置全部的复选框都不勾选
  imgArr.value.forEach((item: any) => {
    imgTableInstance.value.toggleRowSelection(item, false)
  })
  // 选中对应的行时，勾选前面的复选框
  imgTableInstance.value.toggleRowSelection(row, true)
  // 收集图片地址
  skuParams.skuDefaultImg = row.imgUrl
}

// 保存添加的sku信息的按钮的回调
const save = async () => {
  // 整理参数

  // 平台属性(利用reduce来处理)
  skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
    if (next.attrIdAndAttrValueId) {
      let [attrId, valueId] = next.attrIdAndAttrValueId.split(':')
      prev.push({
        attrId: attrId,
        valueId: valueId,
      })
    }
    return prev
  }, [])
  // 销售属性(利用reduce来处理)
  skuParams.skuSaleAttrValueList = saleArr.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
        prev.push({
          saleAttrId: saleAttrId,
          saleAttrValueId: saleAttrValueId,
        })
      }
      return prev
    },
    [],
  )
  // 发送请求[成功或者失败]
  console.log('收集到的skuParams->', skuParams)
  
  let result = await reqAddSku(skuParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '添加SKU成功',
    })
  // 通知父组件切换场景
  $emit('changeScene', { scenes: 0, action: '' })
  } else {
    ElMessage({
      type: 'error',
      message: '添加SKU失败',
    })
  }
}

// 对外暴露的方法
defineExpose({
  initAddSku,
})

//利用defineEmits方法返回的函数去触发自定义事件
let $emit = defineEmits(['changeScene'])
</script>
<script lang="ts">
export default {
  name: 'SkuForm',
}
</script>
<style scoped></style>
